package com.testmanager.testmananger.shuiyou.common.service;

import com.alibaba.fastjson.JSONObject;
import com.testmanager.testmananger.foundation.util.JWTUtil;
import com.testmanager.testmananger.shuiyou.common.domain.SyUserEntity;
import com.testmanager.testmananger.shuiyou.common.respository.SyUserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;



@Service
@Slf4j
public class LoginService {

    //register

    @Autowired
    SyUserRepository userRepository;
    public ResponseEntity register(SyUserEntity userEntity){
        SyUserEntity byUsername = userRepository.findByUsername(userEntity.getUsername());
        if (null != byUsername){
            return ResponseEntity.status(403).body("用户已存在");
        }

        userRepository.save(userEntity);
        return ResponseEntity.ok("success");

    }

    //login

    public ResponseEntity login(String username,String password){
        log.info("login:{},{}",username,password);
        SyUserEntity user = userRepository.findByUsernameAndPassword(username, password);
        if (null == user){
            return ResponseEntity.status(403).body("帐号或密码错误 ");
        }

        String sign = JWTUtil.sign(user.getName(), user.getUsername(), user.getId());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",sign);
        return ResponseEntity.ok(jsonObject);

    }


}
